package com.grm.distributed.lock.service;

import com.grm.distributed.lock.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * redisson-公平锁，拼的是手速、网速 -> 秒杀
 */
@Service
@Slf4j
public class ProductService12 {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 公平锁-按id顺序请求的话，执行的逻辑也是按请求顺序的
     * @param id
     */
    public void testFairLock(Long id) {
        RLock fairLock = redissonClient.getFairLock("fair_lock");
        fairLock.lock();
        try {
            TimeUnit.SECONDS.sleep(10);
            System.out.println("测试公平锁--------------"+id);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            fairLock.unlock();
        }
    }
}
